import { Form, Modal, TreeSelect, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from '../index.less';
import { ProFormInstance, ProFormSelect } from '@ant-design/pro-form';
import ProForm from '@ant-design/pro-form';
import { queryPositionByDep, querySuperiorMent } from '../service';
import { AdminItem, UpdateAdminIdentifyBean } from '../data';
import { queryDepartment } from '../../Department/service';

interface EditRoleFormProps {
  item: AdminItem;
  onSubmit: (values: UpdateAdminIdentifyBean) => Promise<void>;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
  visibleHandler: (flag?: boolean) => void;
}

export default (props: EditRoleFormProps) => {
  const {
    onSubmit: handleUpdate,
    onCancel: handleUpdateModalVisible,
    modalVisible: updateModalVisible,
    item
  } = props;


  const [treeDate, setTreeDate] = useState<any[]>([]);
  const [positionData, setPositionData] = useState<any[]>();
  const [owningAccount, setOwningAccount] = useState<any[]>();
  const [oneTreeDisplay, setOneTreeDisplay] = useState(true);
  const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);
  const [selectDisplay, setSelectDisplay] = useState(false);

  function convertData(data: { id: any; name: any; next_level: string | any[] }) {
    const node = {
      value: data.id,
      title: data.name,
      children: [] as any,
    };
    if (data.next_level && data.next_level.length > 0) {
      for (let i = 0; i < data.next_level.length; i++) {
        const child = convertData(data.next_level[i]);
        node.children.push(child);
      }
    }
    return node;
  }

  useEffect(() => {

    setTreeDate([
      { value: item.department_id, title: item.department_name }
    ])

    setPositionData([
      { value: item.position_id, title: item.position_name }
    ])

    querySuperiorMent(item.position_id).then((res) => {
      if (res && res.code == 0 && res.data.length > 0) {
        setOwningAccount(
          res.data?.map((item: { id: any; name: any }) => {
            return {
              value: item.id,
              label: item.name,
            };
          }),
        );
        setTwoTreeDisplay(true);
        setSelectDisplay(false);
      } else {
        message.error('无上级，请先创建上级');
      }
    });

  }, []);

  const getDepartmentList = async () => {
    queryDepartment().then((res) => {
      if (res && res.code == 0) {
        const data = res?.data;
        const convert = [];
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            convert.push(convertData(data[i]));
          }
          setTreeDate(convert);
        }
      }
    });
  }


  const formRef = useRef<ProFormInstance>();

  return (
    <Modal
      title="修改管理员角色"
      open={updateModalVisible}
      width={550}
      footer={null}
      centered
      onCancel={() => handleUpdateModalVisible(false)}
      afterClose={() => handleUpdateModalVisible(false)}
    >
      <ProForm<UpdateAdminIdentifyBean>
        onFinish={(values) => {
          values.id = item.id
          return handleUpdate(values)
        }}
        onReset={() => {
          formRef.current?.setFieldValue("department_id", undefined)
          formRef.current?.setFieldValue("position_id", undefined)
          formRef.current?.setFieldValue("belong", undefined)
          getDepartmentList()
          setOneTreeDisplay(false)
          setTwoTreeDisplay(true)
          setSelectDisplay(true)
        }}
        formRef={formRef}
        className={styles.stepsAction}
        layout="vertical"
      >

        <Form.Item
          name="department_id"
          label="部门选择"
          rules={[{ required: true, message: '必填' }]}
          initialValue={item.department_id}
        >
          <TreeSelect
            disabled={oneTreeDisplay}
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择部门"
            allowClear
            autoClearSearchValue
            treeDefaultExpandAll
            onChange={(newValue, _labelList) => {
              if (newValue) {
                queryPositionByDep(newValue).then((res) => {
                  if (res && res.code == 0 && res.data.length > 0) {
                    const data = res?.data;
                    const convert = [];
                    for (let i = 0; i < data.length; i++) {
                      convert.push(convertData(data[i]));
                    }
                    setPositionData(convert);
                    setOneTreeDisplay(true);
                    setTwoTreeDisplay(false);
                  } else {
                    message.error("请确保该部门有职位存在")
                  }
                });
              }
            }}
            treeData={treeDate}
          />
        </Form.Item>

        <Form.Item
          name="position_id"
          label="职位选择"
          rules={[{ required: true, message: '必填' }]}
          initialValue={item.position_id}
        >
          <TreeSelect
            disabled={twoTreeDisplay}
            autoClearSearchValue
            showSearch
            onChange={(newValue) => {
              querySuperiorMent(newValue).then((res) => {
                if (res && res.code == 0 && res.data.length > 0) {
                  setOwningAccount(
                    res.data?.map((item: { id: any; name: any }) => {
                      return {
                        value: item.id,
                        label: item.name,
                      };
                    }),
                  );
                  setTwoTreeDisplay(true);
                  setSelectDisplay(false);
                } else {
                  message.error('无上级，请先创建上级');
                }
              });
            }}
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择职位"
            allowClear
            treeDefaultExpandAll
            treeData={positionData}
          />
        </Form.Item>

        <ProFormSelect
          options={owningAccount}
          label={'所属上级'}
          disabled={selectDisplay}
          name="belong"
          rules={[{ required: true, message: '请选择所属企业' }]}
          placeholder="选择所属上级（请先选择职位）"
          initialValue={item.belong}
        />

      </ProForm>


    </Modal>
  );
};

